package cn.hpclub.server.model;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;

/**
 * 实体类 - 管理员
 * 
 */
@TableBind(tableName = "sys_user")
public class Admin extends Model<Admin> implements Serializable{

    private static final long  serialVersionUID = -57555379613217315L;

    public static final String HASH_ALGORITHM   = "SHA-1";
    public static final int    HASH_INTERATIONS = 1024;

    public static final Admin  dao              = new Admin();

    public List<SysRole> getRoleList(){
        String sql = " select r.* from sys_user_role ur, sys_role r "
                + " where ur.is_deleted = 0 and r.is_deleted = 0 and ur.role_id = r.id and ur.user_id = ?";
        return SysRole.dao.find(sql, getStr("id"));
    }

    /**
     * 根据用户名获取管理员对象，若管理员不存在，则返回null（不区分大小写）
     * 
     */
    public Admin getAdminByUsername(String username){
        return dao.findFirst("select * from sys_user u where u.is_deleted = 0 and user_name = ? ", username);
    }

    /**
     * 根据用户名、密码验证管理员
     * 
     * @param username
     *            用户名
     * 
     * @param password
     *            密码
     * 
     * @return 验证是否通过
     */
    public boolean verifyAdmin(String username, String password){
        Admin member = getAdminByUsername(username);
        if(member != null && member.getStr("password").equals(DigestUtils.md5Hex(password))){
            return true;
        } else{
            return false;
        }
    }

    /**
     * 根据用户ID查询该用户所拥有的角色列表
     * 
     * @param userId
     * @return
     */
    public List<String> getRolesName(String adminId){
        String sql = " select r.name from sys_user u, sys_user_role ur, sys_role r where u.is_deleted = 0 and ur.is_deleted = 0 and r.is_deleted = 0 and r.is_active=1 and u.id = ur.user_id and  r.id = ur.role_id and u.id = ?";
        return Db.query(sql, adminId);
    }

    /**
     * 根据用户ID查询该用户所拥有的权限列表
     * 
     * @param userId
     * @return
     */
    public List<String> getAuthoritiesName(String adminId){
        String sql = " select p.permission from sys_user u, sys_user_role ur, sys_role r, sys_role_permission rp, sys_permission p "
                + " where u.is_deleted = 0 and ur.is_deleted = 0 and r.is_deleted = 0 and rp.is_deleted = 0 and p.is_deleted = 0 "
                + " and u.id = ur.user_id and ur.role_id = r.id and r.id = rp.role_id and rp.permission_id = p.id "
                + " and r.is_active=1 and u.id = ?";
        return Db.query(sql, adminId);
    }
}
